package org.hdl.anima.session;

import java.util.List;
import java.util.Random;

import org.hdl.anima.transport.Channel;

import com.google.common.collect.LinkedListMultimap;


/**
 * 
 * @author qiuhd
 * @since  2014年8月15日
 */
public class LocalSessionMgr {
	
	private static LocalSessionMgr instance ;
	private LinkedListMultimap<String, LocalSession> localSessions;
	private final Random random = new Random();
	
	private SessionCloseListener closeListener = new SessionCloseListener() {
		@Override
		public void onSessionClosed(Object session) {
			
			if (session != null) {
				LocalSession localSession = (LocalSession) session;
				localSessions.remove(localSession.getServerId(), localSession);
			}
		}
	};
	
	private LocalSessionMgr() {
		localSessions = LinkedListMultimap.create();
	}

	public static LocalSessionMgr getInstance() {
		if (instance == null) {
			synchronized(ClientSessionMgr.class) {
				if (instance == null) {
					instance = new LocalSessionMgr();
				}
			}
		}
		return instance;
	}
	
	public LocalSession getLocalSession(String serverId) {
		List<LocalSession> localSession = localSessions.get(serverId);
		if (localSession != null) {
			if (localSession.size() == 0) {
				return localSession.get(0);
			}
			int randowIndex = random.nextInt(localSessions.size());
			return localSession.get(randowIndex);
		}
		return null;
	}
	
	public LocalSession createSession(String rsid,Channel channel) {
		LocalSession session = new LocalSession(rsid,channel);
		session.setlistener(closeListener);
		localSessions.put(rsid, session);
		return session;
	}
}

